<?
/**
 * Webapp Session Management
 */
(basename($_SERVER['PHP_SELF']) == basename(__FILE__)) && die('Access Denied');

/**
 * Webapp class for defining properties of webapp users
 */
class appSession {

/**
 * constructor - start session management
 */
function __construct() {
	session_start();
	}

/**
 * Create session for specified user
 * @param array $userAr
 * @param array $appsAr
 * @param array $groupsAr
 * @return bool true on success
 * @return string error message on failures
 */
public function create(&$userAr=null) {
	if (!is_array($userAr))   { return 'invalid user information';   }
	// validate required keys are present
	if (!($this->validateUserInfo(&$userAr) === true)) {
		return 'user info validation failed';
		}
	$_SESSION[WEB_APP_SESS_KEY] = array();
	$_SESSION[WEB_APP_SESS_KEY]['user']   = $userAr;
	return true;
	}

/**
 * Retrieve piece of information about authenticated user.
 * @param string $key - type of user data to return
 * @return mixed
 * @return bool false on failures
 */
public function getUserData($key=null) {
	if (empty($key)) { return false; }
	if (!$this->isAuthenticated()) { return false; }
	if (!array_key_exists($key, $_SESSION[WEB_APP_SESS_KEY]['user'])) {
		return false;
		}
	return $_SESSION[WEB_APP_SESS_KEY]['user'][$key];
	}

/**
 * Is the current user authenticated?
 * @return bool
 */
public function isAuthenticated() {
	return (isset($_SESSION[WEB_APP_SESS_KEY]['user']));
	}

/**
 * Log the current session out
 * @return bool
 */
public function sessionDestroy() {
	if (isset($_SESSION[WEB_APP_SESS_KEY])) {
		unset($_SESSION[WEB_APP_SESS_KEY]);
		}
	return true;
	}

/**
 * Array of required user information key names
 * @return array $keyNames
 */
private function getRequiredUserKeyNames() {
	return array('DisplayName', 'Enabled', 'FirstName', 'Id', 'IsAdmin',
	'LastName', 'Login');
	}

/**
 * Validate required user information keys are present
 * @param array $data
 * @return bool
 */
private function validateUserInfo($data=null) {
	if (!is_array($data)) { return false; }
	$keys = $this->getRequiredUserKeyNames();
	foreach($keys as $key) {
		if (!array_key_exists($key,$data)) { return false; }
		}
	return true;
	}

}

?>